<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sa="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>查看文章</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
    <link rel="stylesheet" th:href="@{/pear/component/layui/css/layui.css}"/>
    <link rel="stylesheet" th:href="@{/pear/admin/css/other/common.css}"/>

</head>
<body>
<iframe style="width: 100%; height: 100vh;" id="iframe"></iframe>
<button type="button" class="layui-btn 
fixed-button" lay-on="test-page-wrap" id="check" sa:hasPermission="infoArticle_enable" style="display: none">去审核
</button>
<button type="button" class="layui-btn 
fixed-button" id="publish" style="display:none;">发布
</button>
<button type="button" class="layui-btn 
fixed-button" id="noPublish" style="display:none;">撤销
</button>
<form id="ID-test-layer-wrapper" style="display: none;" class="layui-form" lay-filter="test">
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-form-item" style="margin-top: 30px">
                <label class="layui-form-label">发布状态</label>
                <div class="layui-input-block">
                    <input type="text" class="layui-input" id="article_publish_status" disabled>
                </div>
            </div>
            <div class="layui-form-item" style="margin-top: 30px">
                <label class="layui-form-label">审核状态</label>
                <div class="layui-input-block">
                    <select lay-filter="article-select-filter" id="article_select">
                        <option value="">请选择文章审核状态</option>
                        <option value="1">审核通过</option>
                        <option value="3">审核不通过</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item" style="display: none" id="articleReason">
                <label class="layui-form-label">理由</label>
                <div class="layui-input-block">
                    <textarea name="reason" placeholder="请输入文章不通过理由"
                              class="layui-textarea"
                              autocomplete="off" maxlength="200" id="reason"></textarea>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn  layui-btn-sm" lay-submit lay-filter="check-save"
                    id="check_save">
                <i class="layui-icon layui-icon-ok"></i>
                确定
            </button>
            <button type="submit" class="layui-btn layui-btn-sm" lay-submit
                    lay-filter="cancel-check" id="cancel_check">
                <i class="layui-icon layui-icon-refresh"></i>
                撤销
            </button>
        </div>
    </div>
</form>
<br/>
<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/pear/pear.js}"></script>
<script th:inline="javascript">
    layui.use(['form', 'jquery', 'laydate', 'util'], function () {
        let form = layui.form;
        let util = layui.util;
        let laydate = layui.laydate;
        let $ = layui.jquery;
        let baseURL = /*[[@{/}]]*/ '';
        // 获取栏目id
        let queryString = window.location.search;
        // 解析查询参数
        let urlParams = new URLSearchParams(queryString);
        const channelUrl = urlParams.get('channelUrl');
        const isChecked = Number(urlParams.get('isChecked'));
        const articleId = urlParams.get('articleId');
        if (channelUrl && articleId) {
            $('#iframe').attr('src', baseURL + joinPaths(channelUrl))
        } else {
            $('#iframe').attr('src', baseURL + "page/error/column404.html")
        }
        let cachedArticle = null; // 用于缓存 channelUrl
        getArticle();

        function getArticle() {
            return new Promise((resolve, reject) => {
                if (cachedArticle) {
                    // 如果已经缓存，直接返回
                    resolve(cachedArticle);
                } else {
                    // 未缓存时发起请求
                    $.ajax({
                        url: baseURL + 'cms/infoArticle/getInfoById',
                        type: 'get',
                        data: {articleId: articleId},
                        success: function (data) {
                            cachedArticle = data.data; // 缓存结果
                            if (isChecked === 2) {
                                if (data.data.status === 1 || data.data.status === 2) {
                                    $('#noPublish').show()
                                    $('#publish').hide()
                                } else {
                                    $('#noPublish').hide()
                                    $('#publish').show()
                                }
                            } else {
                                $('#check').show()
                            }
                            resolve(cachedArticle);
                        },
                    });
                }
            });
        }

        const statusMap = {
            0: "待审核",
            1: "待发布",
            2: "已发布",
            3: "被驳回"
        };
        // 事件
        util.on('lay-on', {
            'test-page-wrap': function () {
                layer.open({
                    type: 1,
                    area: ['450px', '350px'],
                    title: '审核文章',
                    shade: 0.1,
                    content: $('#ID-test-layer-wrapper'), // 捕获的元素
                    success: function () {
                        getArticle()
                            .then(article => {
                                const status = article.status; // 获取文章状态
                                $('#article_publish_status').val(statusMap[status])
                                // 根据状态修改页面
                                if (status === 0) {
                                    // 隐藏撤销按钮和日期选择器
                                    $('#cancel_check').hide();

                                    return; // 直接返回
                                }

                                if (status === 1 || status === 2) {
                                    // 禁用文章状态下拉框，显示发布日期，隐藏保存按钮
                                    $('#article_select').val(1)
                                    $('#article_select').prop('disabled', true);
                                    // $('#publishedDelay').show();
                                    // $('#now').prop('checked', status === 1);
                                    // $('#delay').prop('checked', status === 2);
                                    $('#check_save').hide();
                                    // 填充发布日期

                                }
                                if (status === 3) {
                                    // 禁用文章状态下拉框，隐藏保存按钮和日期选择器
                                    $('#article_select').val(3)
                                    $('#article_select').prop('disabled', true);
                                    $('#check_save').hide();
                                    $('#articleReason').show();
                                    $('#reason').val(article.reason);
                                    $('#reason').prop('disabled', true);
                                }
                                // 更新表单
                                form.render();
                            })
                    },
                });
            }
        });

        form.on('select(article-select-filter)', function (data) {
            if (Number(data.value) === 1) {
                $('#articleReason').hide();

            } else {
                $('#articleReason').show();
                $('#reason').val('')
            }
        });


        // 封装路径拼接函数
        function joinPaths(...segments) {
            return segments
                .map(segment => {
                    // 如果 segment 不是字符串，强制转换为字符串
                    if (typeof segment !== 'string') {
                        segment = String(segment);  // 将非字符串的值转换为字符串
                    }
                    return segment.replace(/\/$/, '').replace(/^\//, '');  // 去除前后多余的斜杠
                })
                .join('/');
        }


        form.on('submit(check-save)', function (data) {
            const status = $('#article_select').val();
            let reasonData = Number(status) === 3 ? $('#reason').val() : null
            if (validateForm(status, reasonData)) {
                check(status, reasonData);
            }
            return false;
        })


        let check = function (status, reasonData) {
            let state = Number(status)
            let loading = layer.load()
            $.ajax({
                url: baseURL + 'cms/infoArticle/updateStatus',
                type: 'post',
                data: {
                    articleId: articleId,
                    status: state,
                    reason: reasonData
                },
                success: function (data) {
                    layer.close(loading)
                    if (data.code === 1000) {
                        layer.msg("操作成功", {
                            icon: 1,
                            time: 2000
                        }, function () {
                            cachedArticle = null;
                            if (isChecked === 2 && state === 1) {
                                $('#publish').hide()
                                $('#noPublish').show()
                            } else if (isChecked === 2 && state === 0) {
                                $('#noPublish').hide()
                                $('#publish').show()
                            } else {
                                $('#article_publish_status').val(statusMap[state])
                                $('#article_select').prop('disabled', true);
                                if (state === 3) {
                                    $('#articleReason').show()
                                    $('#reason').val(reasonData)
                                    $('#reason').prop('disabled', true);
                                }
                                $('#cancel_check').show();
                                $('#check_save').hide();
                            }

                            form.render();
                        });
                    } else {
                        layer.msg(data.msg, {
                            icon: 2,
                            time: 2000
                        });
                    }
                },
                fail: function () {
                    layer.close(loading)
                    layer.msg("服务器错误", {
                        icon: 2,
                        time: 2000
                    });
                }
            })
        }

        function validateForm(status, reasonData) {
            if (!status) {
                layer.msg("请选择文章状态！", {icon: 2, time: 1500});
                return false;
            }
            if (Number(status) === 3) {
                if (!reasonData) {
                    layer.msg("请输入不通过理由！", {icon: 2, time: 1500});
                    return false;
                }
            }
            return true;
        }


        form.on('submit(cancel-check)', function (data) {
            layer.confirm('确定要撤回该文章的审核吗？', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let loading = layer.load()
                $.ajax({
                    url: baseURL + 'cms/infoArticle/updateStatus',
                    type: 'post',
                    data: {
                        articleId: articleId,
                        status: 0,
                        reason: ''
                    },
                    success: function (data) {
                        layer.close(loading)
                        if (data.code === 1000) {
                            layer.msg("撤销成功", {
                                icon: 1,
                                time: 2000
                            }, function () {
                                cachedArticle = null;
                                $('#article_publish_status').val(statusMap[0])
                                $('#article_select').prop('disabled', false);
                                $('#articleReason').prop('disabled', false);
                                $('#article_select').val('');
                                $('#articleReason').hide();
                                $('#reason').val('')
                                $('#cancel_check').hide();
                                $('#check_save').show();
                                form.render();
                            });
                        } else {
                            layer.msg(data.msg, {
                                icon: 2,
                                time: 2000
                            });
                        }
                    },
                    fail: function () {
                        layer.close(loading)
                        layer.msg("服务器错误", {
                            icon: 2,
                            time: 2000
                        });
                    }
                })
            })
            return false;
        })


        $('#publish').on('click', function () {
            layer.confirm('点击确定发布文章', {icon: 3, title: '提示'}, function (index) {
                layer.close(index);
                check(1, null);
            })
        })

        $('#noPublish').on('click', function () {
            layer.confirm('点击确定撤销文章', {icon: 3, title: '提示'}, function (index) {
                layer.close(index);
                check(0, null);
            })
        })

    });
</script>
</body>
</html>

